package com.hro.hro_app.appControler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;

import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.hro.hro_app.dataController.LessonController;
import com.hro.hro_app.dataController.TeacherController;
import com.hro.hro_app.gcm.GCMRegistrationHandler;
import com.hro.hro_app.main.MyApplication;
import com.hro.hro_app.main.RoosterDataChanged;
import com.hro.hro_app.model.Lesson;
import com.hro.hro_app.model.Teacher;
import com.hro.hro_app.util.DateUtil;
import com.hro.hro_app.util.Properties;

public class DownloadRoosterTask extends AsyncTask<Context, String, Void> {

	private RoosterDataChanged roosterDataChanged;

	public DownloadRoosterTask(RoosterDataChanged roosterDataChanged) {

		this.roosterDataChanged = roosterDataChanged;
	}

	@Override
	protected Void doInBackground(Context... params) {

		Log.i(Properties.TAG, "Refresh rooster data gestart");

		Calendar calendar = null;
		BufferedReader in = null;
		HttpURLConnection yc = null;
		CalendarBuilder builder = null;
		URL icalurl = null;

		try {
			icalurl = new URL(Properties.icalurl);
			yc = (HttpURLConnection) icalurl.openConnection();
			in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			builder = new CalendarBuilder();
			calendar = builder.build(in);
		}
		catch (Exception e) {
			Log.e(Properties.TAG, "Geen internet");
		}

		// Als calendar data is geladen dan schrijf weg in database
		if (calendar != null) {

			// Ophalen huidige teachers
			ArrayList<Teacher> teachersBefore = LessonController.getAllTeachers();

			// Maak tabel leeg
			LessonController.deleteTable();

			@SuppressWarnings("unchecked")
			Iterator<Component> i = calendar.getComponents().iterator();
			while (i.hasNext()) {

				Component component = (Component) i.next();

				// Create content values
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
				sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
				Date dtend = null;
				Date dtstart = null;

				try {
					dtstart = sdf.parse(component.getProperty(Property.DTSTART).getValue());
					dtend = sdf.parse(component.getProperty(Property.DTEND).getValue());
				}
				catch (ParseException e) {
					Log.e(Properties.TAG, e.getMessage());
				}

				// Alleen items die nieuwer zijn dan gisteren opslaan in database
				if (dtstart.after(DateUtil.addDays(new Date(), -1))) {

					String teacher = component.getProperty(Property.DESCRIPTION).getValue();
					teacher = teacher.split(" ")[0]; // Split Space vb. HERMM DINF1S
					String lessonId = component.getProperty(Property.UID).getValue();
					String module = component.getProperty(Property.SUMMARY).getValue();
					String location = component.getProperty(Property.LOCATION).getValue();
					Lesson lesson = new Lesson(lessonId, module, teacher, location, dtstart, dtend);

					// Insert into database
					LessonController.saveLesson(lesson);
				}
			}

			ArrayList<Teacher> teachersAfter = LessonController.getAllTeachers();
			Boolean teachListDifferent = false;

			// Size gelijk > controleer waardes
			if (teachersBefore.size() == teachersAfter.size()) {

				for (int iloop = 0; iloop < teachersAfter.size(); iloop++) {

					if (!teachersAfter.get(iloop).getCode().equals(teachersBefore.get(iloop).getCode())) {
						teachListDifferent = true;
					}
				}
			}
			else {
				teachListDifferent = true;
			}

			// Docenten verschillen, werk de server registratie bij.
			if (teachListDifferent) {

				// Wegschrijven docenten in tabel
				TeacherController.saveTeacherList(teachersAfter);

				Log.i(Properties.TAG, "Teacher list verchilt verstuur naar server");
				GCMRegistrationHandler.handle(MyApplication.getAppContext());
			}

			Log.i(Properties.TAG, "Refresh rooster data voltooid");
		}

		return null;
	}

	@Override
	protected void onPostExecute(Void result) {

		Toast.makeText(MyApplication.getAppContext(), "Roosterdata vernieuwd", Toast.LENGTH_LONG).show();

		if (roosterDataChanged != null) {
			roosterDataChanged.roosterDataChanged();
		}

		super.onPostExecute(result);
	}
}